package org.jflame.fx.converter;

import javafx.scene.control.TextFormatter;

/**
 * 用于文本输入框的数字型Formatter
 * 
 * @author charles.zhang
 */
public class NumberFieldFormatter extends TextFormatter<Number> {

    // Pattern.compile("(^-?0.0?[1-9]+$)|(^-?[1-9]\\d*(.0?[1-9]+)?$)");
    /**
     * 构造函数,默认不允许负数和小数
     */
    public NumberFieldFormatter() {
        this(false, false);
    }

    /**
     * 构造函数
     * 
     * @param allowNegative true=允许负数
     * @param allowFloat true=允许小数
     */
    public NumberFieldFormatter(boolean allowNegative, boolean allowFloat) {
        super(change -> {
            String newText = change.getControlNewText();
            if (newText.isEmpty()) {
                return change;
            }
            if (valid(newText, allowNegative, allowFloat)) {
                return change;
            } else {
                return null;
            }
        });
    }

    private static boolean valid(String str, boolean allowNegative, boolean allowFloat) {
        if (allowFloat) {
            try {
                double d = Double.parseDouble(str);
                return !allowNegative ? d >= 0 : true;
            } catch (NumberFormatException e) {
                return false;
            }
        } else {
            try {
                long l = Long.parseLong(str);
                return !allowNegative ? l >= 0 : true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }
}
